package com.code.springboot3.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.code.springboot3.common.BusinessException;
import com.code.springboot3.mapper.ArticleMapper;
import com.code.springboot3.model.dto.AddArticleDto;
import com.code.springboot3.model.dto.UpdateArticleDto;
import com.code.springboot3.model.entity.Article;
import com.code.springboot3.model.entity.Category;
import com.code.springboot3.service.ArticleService;

import com.code.springboot3.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Map;
import java.util.Objects;

/**
* @author Soft
* @description 针对表【article】的数据库操作Service实现
* @createDate 2024-12-26 15:38:06
*/
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article>
    implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    /**
     *
     * @param id
     * @return
     */
    @Override
    public Article getArticleDetail(Integer id, HttpServletRequest request) {
        String authorization = request.getHeader("Authorization");
        Map<String, Object> map = JwtUtil.verifyToken(authorization);
        Integer userId = (Integer) map.get("id");
        Article article = articleMapper.selectById(id);
        boolean b = article.getState().equals("草稿");
        if (!Objects.equals(article.getCreateUser(), userId) && b) {
            throw new BusinessException("无权限");
        }
        return article;
    }

    /**
     * 新增文章
     * @param addArticleDto
     * {
     *   "title": "陕西旅游攻略",
     *   "content": "兵马俑,华清池,法门寺,华山...爱去哪去哪...",
     *   "coverImg": "https://big-event-gwd.oss-cn-beijing.aliyuncs.com/9bf1cf5b-1420-4c1b-91ad-e0f4631cbed4.png",
     *   "state": "草稿",
     *   "categoryId": 2
     * }
     * @param token 令牌
     */
    @Override
    public void addCategory(AddArticleDto addArticleDto, String token) {
        Map<String, Object> map = JwtUtil.verifyToken(token);

        Integer id = (Integer) map.get("id");
        if (id == null || id == 0) {
            throw new BusinessException("添加文章失败");
        }
        Article article = new Article();
        article.setCreateUser(id);
        article.setCoverImg(addArticleDto.getCoverImg());
        article.setState(addArticleDto.getState());
        article.setCategoryId(addArticleDto.getCategoryId());
        article.setTitle(addArticleDto.getTitle());
        article.setContent(addArticleDto.getContent());
        article.setCreateTime(new Date());
        article.setUpdateTime(new Date());
        int insert = articleMapper.insert(article);
        if (insert <= 0) {
            throw new BusinessException("添加文章失败");
        }
    }

    /**
     * 更新文章
     * @param updateArticleDto ```json
     * {
     *     "id":4,
     *     "title": "北京旅游攻略",
     *     "content": "天安门,颐和园,鸟巢,长城...爱去哪去哪...",
     *     "coverImg": "https://big-event-gwd.oss-cn-beijing.aliyuncs.com/9bf1cf5b-1420-4c1b-91ad-e0f4631cbed4.png",
     *     "state": "已发布",
     *     "categoryId": 2
     * }
     * ```
     * @param token token 令牌
     * @return
     */
    @Override
    public Integer updateArticleDetail(UpdateArticleDto updateArticleDto,String token) {
        Map<String, Object> map = JwtUtil.verifyToken(token);
        Article article = articleMapper.selectById(updateArticleDto.getId());
        Integer id = (Integer) map.get("id");
        if (id == null || id == 0 || !id.equals(article.getCreateUser())) {
            throw new BusinessException("无权限");
        }
        article.setCoverImg(updateArticleDto.getCoverImg());
        article.setState(updateArticleDto.getState());
        article.setCategoryId(updateArticleDto.getCategoryId());
        article.setTitle(updateArticleDto.getTitle());
        article.setContent(updateArticleDto.getContent());
        article.setUpdateTime(new Date());
        int update = articleMapper.updateById(article);
        if (update <= 0) {
            throw new BusinessException("更新失败");
        }
        return update;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteArticle(Integer id, String token) {
        // 1. 验证文章是否存在
        Article article = articleMapper.selectById(id);
        if (article == null) {
            throw new BusinessException("文章不存在");
        }

        // 2. 验证用户权限
        Map<String, Object> claims = JwtUtil.verifyToken(token);
        Integer userId = (Integer) claims.get("id");
        
        // 只能删除自己的文章
        if (!Objects.equals(article.getCreateUser(), userId)) {
            throw new BusinessException("无权删除此文章");
        }

        // 3. 删除文章
        int rows = articleMapper.deleteById(id);
        if (rows != 1) {
            throw new BusinessException("删除文章失败");
        }
    }
}




